package com.shopping.controller;

import com.shopping.bean.User;
import com.shopping.bean.UserAddress;
import com.shopping.service.IUserAddressService;
import com.shopping.util.LayData;
import com.shopping.util.SYS;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("address")
public class UserAddressController {
    @Autowired
    IUserAddressService addressService;
    @RequestMapping("add")
    @ResponseBody
    public LayData add(HttpSession session, UserAddress address){
        int userid = SYS.getLoginUserID(session);
        address.setUserid(userid);
        //检查收货地址的数量不能超过上限
        List list=addressService.getAddressByUserID(userid);
        if (list.size()<SYS.ADDREE_MAX_NUMBER){
            addressService.add(address);
            return LayData.success(200,"添加成功");
        }else {
            return LayData.success(400,"收货地址数量不能超过上限"+SYS.ADDREE_MAX_NUMBER);
        }

    }
    @RequestMapping("edit")
    @ResponseBody
    public LayData edit(UserAddress address) {
        return LayData.success(200,"编辑成功",addressService.edit(address));
    }
    @RequestMapping("delete")
    @ResponseBody
    public LayData delete(int id) {
        return LayData.success(200,"删除成功",addressService.delete(id));
    }
    @RequestMapping("getaddressbyid")
    @ResponseBody
    public LayData getAddressByID(int id) {
        return LayData.success(addressService.getAddressByID(id));
    }
    @RequestMapping("getaddressbyuserid")
    @ResponseBody
    public LayData getAddressByUserID(HttpSession session) {
        int userid=SYS.getLoginUserID(session);
        return LayData.success(200,"",addressService.getAddressByUserID(userid));
    }
    @RequestMapping("setdefault")
    @ResponseBody
    public LayData setDefault(HttpSession session, int addressid) {
        if (session == null) {
            return LayData.success(400, "会话为空，请重新登录");
        }
        if (addressid <= 0) {
            return LayData.success(400, "地址 ID 无效");
        }
        int userid = SYS.getLoginUserID(session);
        return LayData.success(200, "设置成功", addressService.setDefault(userid, addressid));
    }
}
